﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MSExcel = Microsoft.Office.Interop.Excel;
using System.Diagnostics;
using System.Reflection.Emit;
using System.Threading;
using System.Reflection;
using System.Collections;

namespace UltraToys.Excel.Interop
{
    public class VBAMacro
    {
        private MSExcel.Application _Application;
        private List<string> _MacroNames;

        public VBAMacro(MSExcel.Application App)
        {
            Microsoft.Vbe.Interop.VBProject ProjectItem;
            Microsoft.Vbe.Interop.VBComponent Component;

            _MacroNames = new List<string>();
            _Application = App;

            for (int i = 1; i <= App.VBE.VBProjects.Count; i++)
            {
                if (App.VBE.VBProjects.Item(i).Protection == Microsoft.Vbe.Interop.vbext_ProjectProtection.vbext_pp_none)
                {
                    ProjectItem = App.VBE.VBProjects.Item(i);

                    for (int j = 1; j <= ProjectItem.VBComponents.Count; j++)
                    {
                        Component = ProjectItem.VBComponents.Item(j);

                        if (Component.CodeModule.CountOfLines > 0)
                        {
                            ParseCode(Component.CodeModule.get_Lines(1, Component.CodeModule.CountOfLines), Component.Name);
                        }                        
                    }
                }
            }
        }

        private void ParseCode(string Code, string Name)
        {
            
        }

        public void ExecuteMacro(string Name)
        {
            ExecuteMacro(Name, null);
        }

        public void ExecuteMacro(string Name, object [] Arguments)
        {
            ArrayList Params;

            if (Arguments == null)
            {
                Params = new ArrayList();
            }
            else
            {
                Params = new ArrayList(Arguments);
            }

            
            if (Params.Count < 30)
            {
                for (int i = Params.Count; i < 30; i++)
                {
                    Params.Add(System.Type.Missing);
                }
            }

            _Application.Run(Name, Params[0], Params[1], Params[2], Params[3], Params[4], Params[5], Params[6],
                                   Params[7], Params[8], Params[9], Params[10], Params[11], Params[12], Params[13],
                                   Params[14], Params[15], Params[16], Params[17], Params[18], Params[19], Params[20],
                                   Params[21], Params[22], Params[23], Params[24], Params[25], Params[26], Params[27],
                                   Params[28], Params[29]);
        }

        public List<string> Macros 
        {
            get
            {
                return _MacroNames;
            }
        }
    }
}
